from odoo import fields, models, api
from odoo.exceptions import UserError

from ...functions.operation_control_fc import OperationControlFC


class RPCourier(models.Model):
    _name = "rp.courier"
    _description = '承运商'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _sql_constraints = [('unique_name', 'UNIQUE(name)', '承运商名称必须唯一'),
                        ('unique_code', 'UNIQUE(code)', '承运商编码必须唯一')]

    def _default_get_cm3kg(self):
        cm3kg = self.env['uom.uom'].search([('name', '=', 'cm³/kg')])
        return cm3kg.id if cm3kg else False

    name = fields.Char(string='名称', required=True, copy=False, index=True, tracking=True)
    code = fields.Char(string='编码', readonly=True, copy=False, index=True, tracking=True)

    photo = fields.Binary(string='图片', tracking=True)

    # 头尾程
    operation_display = fields.Char(string='头尾程', default='-,-,-,-', compute='_depends_fulfill_operation', store=True, tracking=True)
    operation_dropoff = fields.Boolean(string='网点收件', default=True)
    operation_pickup = fields.Boolean(string='上门取件', default=True)
    operation_collect = fields.Boolean(string='网点取件', default=True)
    operation_delivery = fields.Boolean(string='送货上门', default=True)

    volume_weight_ids = fields.Many2many(string='体积重', comodel_name='rp.volume.weight', required=True,
                                         relation='rp_courier_and_volume_weight_rel', column1='courier_id', column2='volume_weight_id')

    package_type_ids = fields.Many2many(string='包裹类型', comodel_name='rp.package.type', required=True,
                                        relation='rp_courier_and_package_type_rel', column1='courier_id', column2='package_type_id')
    package_standards_ids = fields.Many2many(string='包裹标准', comodel_name='rp.package.standards',
                                             relation='rp_courier_and_package_standards_rel', column1='courier_id', column2='package_standards_id')
    value_added_ids = fields.Many2many(string='增值服务', comodel_name='rp.value.added.service',
                                       relation='rp_courier_and_value_added_rel', column1='courier_id', column2='value_added_id')

    courier_mail_route_ids = fields.One2many(string='承运商邮路', comodel_name='rp.courier.mail.route', inverse_name='courier_id')
    courier_token_ids = fields.One2many(string='承运商令牌', comodel_name='rp.courier.token', inverse_name='courier_id')

    # 通过双向的m2o建立一对一关系
    cost_template_id = fields.Many2one(string='成本价模板', comodel_name='rp.courier.cost.template', tracking=True)
    holiday_template_id = fields.Many2one(string='节假日模板', comodel_name='rp.holiday.template', tracking=True)
    rp_holiday_template_lines = fields.One2many(string='节假日模板明细', comodel_name='rp.holiday.template.line', inverse_name='rp_courier_id')

    shipper_id = fields.Many2one(string='托运商', comodel_name='rp.shipper', readonly=True, tracking=True)

    paper_id = fields.Many2one(string='纸张格式', comodel_name='report.paperformat')
    remarks = fields.Text(string='备注')

    @api.depends('operation_pickup', 'operation_dropoff', 'operation_delivery', 'operation_collect')
    def _depends_fulfill_operation(self):
        for s in self:
            operation = OperationControlFC(self.env, s.operation_dropoff, s.operation_pickup, s.operation_collect, s.operation_delivery)

            s.write({'operation_display': operation.fulfill_display(),
                     'value_added_ids': [(6, 0, operation.update_value_add_list(s.value_added_ids.ids))]})

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            code = vals.get('code', False)
            if not code:
                vals.update({'code': str(vals.get('name'))[:2].upper()})
        result = super(RPCourier, self).create(vals_list)
        return result

    def write(self, values):
        result = super(RPCourier, self).write(values)
        return result

    @api.onchange('value_added_ids')
    def _onchange_value_added_ids(self):
        """ 头尾程的增值服务不允许删除 """
        if self.value_added_ids:
            operation = OperationControlFC(self.env, self.operation_dropoff, self.operation_pickup, self.operation_collect, self.operation_delivery)
            if not operation.monitor_value_add_list(self.value_added_ids.ids):
                raise UserError('增值服务中的头尾程不允许删除')

    @api.onchange('cost_template_id')
    def _onchange_cost_template(self):
        if self.cost_template_id:
            # 在onchange或depends中无法通过self.id获取当前记录ID,需要使用_origin
            template_rcds = self.env['rp.courier.cost.template'].search([('courier_id', '=', self._origin.id)])
            for t in template_rcds:
                t.active_flag = False
            self.cost_template_id.active_flag = True

    @api.onchange('holiday_template_id')
    def _onchange_holiday_template_id(self):
        lines = self.env['rp.holiday.template.line']
        if self.holiday_template_id:
            template_lines = self.holiday_template_id.rp_holiday_template_lines + self.holiday_template_id.rp_week_template_lines
            for line in template_lines:
                lines |= line.copy({
                    'rp_holiday_template_id': False,
                })
        self.rp_holiday_template_lines = [(6, 0, lines.ids)]
